<?php
class LoginTaobaoAction extends PiscesAction
{
	public function __construct()
	{
		parent::__construct();
	}

	public function execute()
	{
		
		$topParams 	= $this->context->get('top_parameters');
		$topSign	= $this->context->get('top_sign');
		$topSession	= $this->context->get('top_session');
		if(empty($topParams) || empty($topSign) || empty($topSession))
		{
			$this->goToHomePage();
		}
		
		$loginSetting = Util::loadSetting('login');
		$appKey = '12502127';//$loginSetting['key'];
		$appSecret = '77219ab14592aa6740fb0446590f131c';//$loginSetting['secret'];
		$sign = base64_encode(md5($appKey.$topParams.$topSession.$appSecret, true));
		if($sign!=$topSign)
		{
			
			$this->goToHomePage();
		}
		
		$str	= base64_decode($topParams);
		$tmp	= explode('&',$str);
		$info	= array();
		foreach($tmp as $v)
		{
			$tt				= explode('=',$v);
			if(count($tt)==2)
			{
				$info[$tt[0]]	= $tt[1];
			}
		}
		$userName	= iconv('GBK','UTF-8',$info['visitor_nick']);
		if(empty($userName))
		{
			$this->goToHomePage();
		}
		
		//从数据库中取用户
		$userService = new UserService();
		$user = $userService->getUserByTaobaoNick($userName);
		if(!$user)
		{
			$userInfo = array();
			$userInfo['username']= $userName;
			$userInfo['password']= Util::random(32);
			$userInfo['secques']= Util::random(6);
			$userInfo['account']= $userName;
			$userInfo['account_type']= 1;//淘宝
			$userInfo['login_times']= 1;
			$userInfo['last_login_time']= Util::now();
			$userInfo['last_login_ip']= Util::ip2number($this->getIp());
			$id = $userService->add($userInfo);
			if($id<=0)
			{
				$this->goToHomePage();
			}
			$user = $userService->get($id);
		}
		else
		{
			//更新登录信息
			$userInfo = array();
			$userInfo['login_times'] = $user['login_times']+1;
			$userInfo['last_login_time']= Util::now();
			$userInfo['last_login_ip']= Util::ip2number($this->getIp());
			$userService->update($user['id'], $userInfo);
		}
		
		if(!$user)
		{
			$this->goToHomePage();
		}
		
		//写cookie,20分钟内登录有效
		$expire		= time() + 1200;
		$authCode 	= $user['id'] . "\t" . $user['username']. "\t" .$user['password']. "\t" .$expire;
		C("LtCookie")->setCookie('user_auth', $authCode, $expire);
		
		$this->goToHomePage();
	}
	
	//跳转到首页
	private function goToHomePage()
	{
		$this->redirect($this->data['baseurl']);
	}
}
